<?php

namespace app\admin\controller;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\tool\CommonTool;
use jianyan\excel\Excel;
use think\App;
use think\facade\Db;

/**
 * Class Admin
 * @package app\admin\controller
 * @ControllerAnnotation(title="订单管理")
 */
class Orders extends AdminController
{

    protected $sort = [
        'id' => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Orders();

        $this->wages = new \app\admin\model\Wages();
        
        $this->assign('getTypeList', $this->model->getTypeList());

        $this->assign('getProjectStatusList', $this->model->getProjectStatusList());

        $this->assign('getStateList', $this->model->getStateList());

        $this->assign('getUsersList', $this->model->getUsersList());

    }

    /**
     * @NodeAnotation(title="进行中")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFieds')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            // 强行非关联搜索where拦截
            foreach ($where as $k => $v){
                if ($v[0] == 'true_name'){
                    $where[$k] = whereHook($v, 'uid', '\app\admin\model\Users','uid');
                }
            }
            $where[] = ['state', '=', 0];
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            foreach ($list as $k => $v){
                $list[$k]['true_name'] = \app\admin\model\Users::where('uid', $v['uid'])->value('true_name');
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="已完成")
     */
    public function index1()
    {
        if ($this->request->isAjax()) {
            if (input('selectFieds')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            // 强行非关联搜索where拦截
            foreach ($where as $k => $v){
                if ($v[0] == 'true_name'){
                    $where[$k] = whereHook($v, 'uid', '\app\admin\model\Users','uid');
                }
            }
            $where[] = ['state', '=', 1];
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            foreach ($list as $k => $v){
                $list[$k]['true_name'] = \app\admin\model\Users::where('uid', $v['uid'])->value('true_name');
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="已结算")
     */
    public function index2()
    {
        if ($this->request->isAjax()) {
            if (input('selectFieds')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            // 强行非关联搜索where拦截
            foreach ($where as $k => $v){
                if ($v[0] == 'true_name'){
                    $where[$k] = whereHook($v, 'uid', '\app\admin\model\Users','uid');
                }
            }
            $where[] = ['state', '=', 2];
            $where[] = ['ratio_amount', '<>', 0];
            $where[] = ['ratio_time', '<>', ''];
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            foreach ($list as $k => $v){
                $list[$k]['true_name'] = \app\admin\model\Users::where('uid', $v['uid'])->value('true_name');
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="订单查看")
     */
    public function view()
    {
        $row = $this->model->find($this->request->param($this->model->getPk()));
        empty($row) && $this->error('订单不存在');
        $row['uid'] = $this->model->getUsersList()[$row['uid']] ?? '无';
        $row['state'] = $this->model->getStateList()[$row['state']] ?? '无';
        $row['type'] = $this->model->getTypeList()[$row['type']] ?? '无';
        $row['project_status'] = $this->model->getProjectStatusList()[$row['project_status']] ?? '无';
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="订单编辑")
     */
    public function edit()
    {
        $row = $this->model->find($this->request->param($this->model->getPk()));
        empty($row) && $this->error('数据不存在');
        if ($row->state == 1){
            $this->error('订单已完成,无法修改');
        }
        if ($row->state == 2){
            $this->error('订单已结算,无法修改');
        }
        if ($this->request->isAjax()) {
            $post = $this->request->except(['ratio_amount','ratio_time'],'post');
            $rule = [];
            $this->validate($post, $rule);
            // 已收金额大于等于成交金额的时候,订单自动变为已完成
            if ($post['pay_amount'] >= $post['total_amount']){
                $post['state'] = 1;
            }
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="订单导出")
     */
    public function export()
    {
        list($page, $limit, $where) = $this->buildTableParames();
        $tableName = $this->model->getName();
        $tableName = CommonTool::humpToLine(lcfirst($tableName));
        $prefix = config('database.connections.mysql.prefix');
        $dbList = Db::query("show full columns from {$prefix}{$tableName}");
        $header = [];
        foreach ($dbList as $vo) {
            $comment = !empty($vo['Comment']) ? $vo['Comment'] : $vo['Field'];
            if (!in_array($vo['Field'], $this->noExportFileds)) {
                $header[] = [$comment, $vo['Field']];
            }
        }
        $list = $this->model
            ->where($where)
            ->limit(100000)
            ->order($this->sort)
            ->select()
            ->toArray();
        $fileName = time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }
}